package com.zcloud.eventstudydemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zcloud.eventstudydemo.dto.RestWebResponse;
import com.zcloud.eventstudydemo.entity.Event;
import com.zcloud.eventstudydemo.entity.MilitaryDictionary;
import com.zcloud.eventstudydemo.mapper.EventMapper;
import com.zcloud.eventstudydemo.mapper.MilitaryDictionaryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/military-dictionary")
public class MilitaryDictionaryController {

    @Autowired
    private MilitaryDictionaryMapper militaryDictionaryMapper;
    
    @Autowired
    private EventMapper eventMapper;

    /**
     * 获取三级字典树结构
     * @return 字典树
     */
    @GetMapping("/tree")
    public RestWebResponse<List<MilitaryDictionary>> getDictionaryTree() {
        // 查询所有顶级节点（海军编成、武器装备、军事行动）
        QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        wrapper.orderByAsc("sort");
        List<MilitaryDictionary> topLevel = militaryDictionaryMapper.selectList(wrapper);

        // 递归查询子节点
        for (MilitaryDictionary top : topLevel) {
            fillChildren(top);
        }

        return RestWebResponse.success(topLevel);
    }

    /**
     * 递归填充子节点
     * @param parent 父节点
     */
    private void fillChildren(MilitaryDictionary parent) {
        QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parent.getId());
        wrapper.orderByAsc("sort");
        List<MilitaryDictionary> children = militaryDictionaryMapper.selectList(wrapper);
        parent.setChildren(children);

        // 继续递归填充子节点的子节点
        for (MilitaryDictionary child : children) {
            fillChildren(child);
        }
    }




    /**
     * 获取支持搜索的三级字典树结构
     * @param keyword 搜索关键词
     * @return 字典树
     */
    @GetMapping("/tree/search")
    public RestWebResponse<List<MilitaryDictionary>> getDictionaryTreeWithSearch(@RequestParam(required = false) String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            // 如果没有搜索关键词，返回完整的树形结构
            return getDictionaryTree();
        }

        // 查询所有顶级节点（level=1）
        QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        wrapper.orderByAsc("sort");
        List<MilitaryDictionary> topLevel = militaryDictionaryMapper.selectList(wrapper);

        // 递归填充子节点并进行搜索过滤
        for (MilitaryDictionary top : topLevel) {
            fillChildrenWithSearch(top, keyword);
        }

        // 过滤掉所有子节点都不匹配的顶级节点
        List<MilitaryDictionary> result = new ArrayList<>();
        for (MilitaryDictionary top : topLevel) {
            if (top.getChildren() != null && !top.getChildren().isEmpty()) {
                result.add(top);
            } else if (top.getName().contains(keyword)) {
                // 如果顶级节点本身匹配，也保留
                result.add(top);
            }
        }

        return RestWebResponse.success(result);
    }

    /**
     * 递归填充子节点并进行搜索过滤
     * @param parent 父节点
     * @param keyword 搜索关键词
     */
    private void fillChildrenWithSearch(MilitaryDictionary parent, String keyword) {
        // 查询所有子节点
        QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parent.getId());
        wrapper.orderByAsc("sort");
        List<MilitaryDictionary> children = militaryDictionaryMapper.selectList(wrapper);

        // 创建新的子节点列表，用于存储匹配的节点
        List<MilitaryDictionary> matchedChildren = new ArrayList<>();

        // 遍历所有子节点
        for (MilitaryDictionary child : children) {
            // 检查当前节点或其任意后代是否包含关键词
            if (isMatchOrHasMatchedDescendant(child, keyword)) {
                // 递归填充子节点
                fillChildrenWithSearch(child, keyword);
                matchedChildren.add(child);
            }
        }

        // 设置匹配的子节点
        parent.setChildren(matchedChildren);
    }

    /**
     * 判断节点自身或其任意后代是否包含关键词
     * @param node 节点
     * @param keyword 关键词
     * @return 是否匹配
     */
    private boolean isMatchOrHasMatchedDescendant(MilitaryDictionary node, String keyword) {
        // 当前节点是否匹配
        if (node.getName().contains(keyword)) {
            return true;
        }

        // 检查子节点是否存在且是否包含匹配的后代
        if (node.getChildren() != null && !node.getChildren().isEmpty()) {
            for (MilitaryDictionary child : node.getChildren()) {
                if (isMatchOrHasMatchedDescendant(child, keyword)) {
                    return true;
                }
            }
        }

        // 查询数据库中的实际子节点（避免缓存问题）
        QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", node.getId());
        List<MilitaryDictionary> realChildren = militaryDictionaryMapper.selectList(wrapper);
        if (realChildren != null && !realChildren.isEmpty()) {
            for (MilitaryDictionary child : realChildren) {
                if (isMatchOrHasMatchedDescendant(child, keyword)) {
                    return true;
                }
            }
        }

        return false;
    }



    /**
     * 添加同级分类
     * @param dictionary 新增字典项，需包含 parentId 和 name
     * @return 添加结果
     */
    @PostMapping("/add-sibling")
    public RestWebResponse<String> addSibling(@RequestBody MilitaryDictionary dictionary) {
        if (dictionary.getParentId() == null || dictionary.getName() == null || dictionary.getName().trim().isEmpty()) {
            return new RestWebResponse<>("400", "父节点ID和名称不能为空", null);
        }

        // 查询父节点
        MilitaryDictionary parent = null;
        if (dictionary.getParentId() != 0) {
            parent = militaryDictionaryMapper.selectById(dictionary.getParentId());
            if (parent == null) {
                return new RestWebResponse<>("404", "父节点不存在", null);
            }
        }

        // 设置level - 添加的是父节点的子节点，所以level为父节点level+1
        int level = (parent == null) ? 1 : parent.getLevel() + 1;
        dictionary.setLevel(level);

        // 自动生成code
        String code = generateCode(dictionary.getParentId(), level);
        if (code == null) {
            return new RestWebResponse<>("500", "无法生成分类编码", null);
        }
        dictionary.setCode(code);

        // 设置sort值为同级节点中的最大值加1
        QueryWrapper<MilitaryDictionary> sortWrapper = new QueryWrapper<>();
        sortWrapper.eq("parent_id", dictionary.getParentId());
        sortWrapper.orderByDesc("sort");
        List<MilitaryDictionary> siblings = militaryDictionaryMapper.selectList(sortWrapper);
        int maxSort = 0;
        if (!siblings.isEmpty()) {
            maxSort = siblings.get(0).getSort();
        }
        dictionary.setSort(maxSort + 1);

        dictionary.setCreateTime(LocalDateTime.now());
        dictionary.setUpdateTime(LocalDateTime.now());
        
        int result = militaryDictionaryMapper.insert(dictionary);

        if (result > 0) {
            return RestWebResponse.success("同级分类添加成功");
        } else {
            return new RestWebResponse<>("500", "同级分类添加失败", null);
        }
    }

    /**
     * 根据父节点和层级生成code
     * @param parentId 父节点ID
     * @param level 层级
     * @return 生成的code
     */
    private String generateCode(Integer parentId, int level) {
        if (level == 1) {
            // 顶级节点，使用字母序列 A, B, C...
            QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
            wrapper.eq("level", 1);
            wrapper.orderByDesc("code");
            List<MilitaryDictionary> topLevelNodes = militaryDictionaryMapper.selectList(wrapper);
            
            if (topLevelNodes.isEmpty()) {
                return "A";
            }
            
            // 获取最后一个节点的code并递增
            String lastCode = topLevelNodes.get(0).getCode();
            if (lastCode != null && lastCode.length() == 1) {
                char nextChar = (char)(lastCode.charAt(0) + 1);
                return String.valueOf(nextChar);
            }
            return null;
        } else {
            // 非顶级节点，格式为父节点code+两位数字
            MilitaryDictionary parent = militaryDictionaryMapper.selectById(parentId);
            if (parent == null) {
                return null;
            }
            
            String parentCode = parent.getCode();
            QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", parentId);
            wrapper.orderByDesc("code");
            List<MilitaryDictionary> siblings = militaryDictionaryMapper.selectList(wrapper);
            
            int nextNumber = 1;
            if (!siblings.isEmpty()) {
                // 从最后一个兄弟节点的code中提取数字部分并加1
                String lastCode = siblings.get(0).getCode();
                if (lastCode != null && lastCode.startsWith(parentCode)) {
                    try {
                        String numberPart = lastCode.substring(parentCode.length());
                        nextNumber = Integer.parseInt(numberPart) + 1;
                    } catch (NumberFormatException e) {
                        // 如果解析失败，则使用默认值1
                    }
                }
            }
            
            return parentCode + String.format("%02d", nextNumber);
        }
    }

    /**
     * 添加子分类
     * @param dictionary 新增字典项，需包含 parentId 和 name
     * @return 添加结果
     */
    @PostMapping("/add-child")
    public RestWebResponse<String> addChild(@RequestBody MilitaryDictionary dictionary) {
        if (dictionary.getParentId() == null || dictionary.getName() == null || dictionary.getName().trim().isEmpty()) {
            return new RestWebResponse<>("400", "父节点ID和名称不能为空", null);
        }

        // 查询父节点是否存在且层级不超过3
        MilitaryDictionary parent = militaryDictionaryMapper.selectById(dictionary.getParentId());
        if (parent == null) {
            return new RestWebResponse<>("404", "父节点不存在", null);
        }
        if (parent.getLevel() >= 3) {
            return new RestWebResponse<>("400", "层级已达上限，无法添加子分类", null);
        }

        // 设置level
        dictionary.setLevel(parent.getLevel() + 1);
        
        // 自动生成code
        String code = generateCode(dictionary.getParentId(), dictionary.getLevel());
        if (code == null) {
            return new RestWebResponse<>("500", "无法生成分类编码", null);
        }
        dictionary.setCode(code);

        // 设置sort值为同级节点中的最大值加1
        QueryWrapper<MilitaryDictionary> sortWrapper = new QueryWrapper<>();
        sortWrapper.eq("parent_id", dictionary.getParentId());
        sortWrapper.orderByDesc("sort");
        List<MilitaryDictionary> siblings = militaryDictionaryMapper.selectList(sortWrapper);
        int maxSort = 0;
        if (!siblings.isEmpty()) {
            maxSort = siblings.get(0).getSort();
        }
        dictionary.setSort(maxSort + 1);

        dictionary.setCreateTime(LocalDateTime.now());
        dictionary.setUpdateTime(LocalDateTime.now());
        int result = militaryDictionaryMapper.insert(dictionary);

        if (result > 0) {
            return RestWebResponse.success("子分类添加成功");
        } else {
            return new RestWebResponse<>("500", "子分类添加失败", null);
        }
    }

    /**
     * 修改字典项
     * @param dictionary 字典项对象
     * @return 修改结果
     */
    @PostMapping("/update")
    public RestWebResponse<String> updateDictionary(@RequestBody MilitaryDictionary dictionary) {
        // 查询原始字典项
        MilitaryDictionary originalDictionary = militaryDictionaryMapper.selectById(dictionary.getId());
        if (originalDictionary == null) {
            return new RestWebResponse<>("404", "字典项不存在", null);
        }
        
        dictionary.setUpdateTime(LocalDateTime.now());
        int result = militaryDictionaryMapper.updateById(dictionary);
        
        // 如果名称发生了变化，需要更新Event表中的eventTypeName字段
        if (result > 0 && dictionary.getName() != null && 
            !dictionary.getName().equals(originalDictionary.getName())) {
            updateEventTypeNameForAllLevels(originalDictionary, dictionary.getName());
        }

        if (result > 0) {
            return RestWebResponse.success("字典项更新成功");
        } else {
            return new RestWebResponse<>("500", "字典项更新失败", null);
        }
    }
    
    /**
     * 更新所有层级相关的Event表中的eventTypeName字段
     * @param originalDictionary 原始字典项
     * @param newName 新名称
     */
    private void updateEventTypeNameForAllLevels(MilitaryDictionary originalDictionary, String newName) {
        // 构建原始完整路径名称
        String originalFullPathName = buildFullPathName(originalDictionary);
        
        // 构建新的完整路径名称
        String newFullPathName = originalFullPathName.replace(originalDictionary.getName(), newName);
        
        // 更新完全匹配的记录
        updateEventTypeName(originalFullPathName, newFullPathName);
        
        // 如果有子节点，还需要更新所有包含该路径的记录
        updateEventTypeNameForChildren(originalDictionary, originalFullPathName, newFullPathName);
    }
    
    /**
     * 更新Event表中完全匹配的eventTypeName字段
     * @param originalFullPathName 原始完整路径名称
     * @param newFullPathName 新完整路径名称
     */
    private void updateEventTypeName(String originalFullPathName, String newFullPathName) {
        QueryWrapper<Event> wrapper = new QueryWrapper<>();
        wrapper.eq("event_type_name", originalFullPathName);
        
        Event updateEvent = new Event();
        updateEvent.setEventTypeName(newFullPathName);
        updateEvent.setUpdateTime(LocalDateTime.now());
        
        eventMapper.update(updateEvent, wrapper);
    }
    
    /**
     * 更新包含该节点路径的所有子节点相关记录
     * @param originalDictionary 原始字典项
     * @param originalFullPathName 原始完整路径名称
     * @param newFullPathName 新完整路径名称
     */
    private void updateEventTypeNameForChildren(MilitaryDictionary originalDictionary, String originalFullPathName, String newFullPathName) {
        // 查询所有以原始路径开头的事件记录
        QueryWrapper<Event> wrapper = new QueryWrapper<>();
        wrapper.likeRight("event_type_name", originalFullPathName + "-");
        
        List<Event> events = eventMapper.selectList(wrapper);
        for (Event event : events) {
            String originalEventTypeName = event.getEventTypeName();
            // 直接替换前缀部分
            String newEventTypeName = originalEventTypeName.replaceFirst(
                java.util.regex.Pattern.quote(originalFullPathName), 
                newFullPathName);
            
            Event updateEvent = new Event();
            updateEvent.setEventTypeName(newEventTypeName);
            updateEvent.setUpdateTime(LocalDateTime.now());
            
            QueryWrapper<Event> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("id", event.getId());
            eventMapper.update(updateEvent, updateWrapper);
        }
    }
    
    /**
     * 构建字典项的完整路径名称
     * @param dictionary 字典项
     * @return 完整路径名称
     */
    private String buildFullPathName(MilitaryDictionary dictionary) {
        List<String> pathNames = new ArrayList<>();
        pathNames.add(dictionary.getName());
        
        // 向上遍历父节点
        Integer parentId = dictionary.getParentId();
        while (parentId != null && parentId != 0) {
            MilitaryDictionary parent = militaryDictionaryMapper.selectById(parentId);
            if (parent == null) {
                break;
            }
            pathNames.add(0, parent.getName()); // 添加到列表开头
            parentId = parent.getParentId();
        }
        
        return String.join("-", pathNames);
    }

    /**
     * 重命名字典项
     * @param id 字典项ID
     * @param name 新名称
     * @return 修改结果
     */
    @PostMapping("/rename")
    public RestWebResponse<String> rename(@RequestParam Integer id, @RequestParam String name) {
        if (id == null || name == null || name.trim().isEmpty()) {
            return new RestWebResponse<>("400", "ID和名称不能为空", null);
        }

        MilitaryDictionary dict = militaryDictionaryMapper.selectById(id);
        if (dict == null) {
            return new RestWebResponse<>("404", "字典项不存在", null);
        }

        dict.setName(name.trim());
        dict.setUpdateTime(LocalDateTime.now());
        int result = militaryDictionaryMapper.updateById(dict);

        if (result > 0) {
            return RestWebResponse.success("重命名成功");
        } else {
            return new RestWebResponse<>("500", "重命名失败", null);
        }
    }

    /**
     * 删除字典项（原方法保留）
     * @param id 字典项ID
     * @return 删除结果
     */
    @GetMapping("/delete/{id}")
    public RestWebResponse<String> deleteDictionary(@PathVariable Integer id) {
        // 检查是否有子节点
        QueryWrapper<MilitaryDictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        long count = militaryDictionaryMapper.selectCount(wrapper);

        if (count > 0) {
            return new RestWebResponse<>("500", "该字典项存在子节点，无法删除", null);
        }

        int result = militaryDictionaryMapper.deleteById(id);

        if (result > 0) {
            return RestWebResponse.success("字典项删除成功");
        } else {
            return new RestWebResponse<>("500", "字典项删除失败", null);
        }
    }
}